package com.keon.jianbao.ui.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.keon.jianbao.AppContext;
import com.keon.jianbao.AppManager;
import com.keon.jianbao.R;
import com.keon.jianbao.api.Api;
import com.keon.jianbao.api.SimpleHandler;
import com.keon.jianbao.api.WXApi;
import com.keon.jianbao.base.BaseActivity;
import com.keon.jianbao.bean.Login;
import com.keon.jianbao.bean.Result;
import com.keon.jianbao.bean.User;
import com.keon.jianbao.enu.PasswordActivtyType;
import com.keon.jianbao.util.ConstantUtils;
import com.keon.jianbao.util.DialogHelp;
import com.keon.jianbao.util.JsonUtils;
import com.keon.jianbao.util.StringUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.apache.http.Header;
import org.json.JSONException;

import java.lang.reflect.Field;
import java.util.HashMap;

import butterknife.Bind;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by keon on 2015/9/6.
 */
public class LoginActivity extends BaseActivity {

    public static final int TYPE_WX = 2;
    public static final int TYPE_QQ = 1;
    public static final int TYPE_WEIBO = 3;

    Tencent mTencent;
//    private AuthInfo mAuthInfo;
    /**
     * 注意：SsoHandler 仅当 SDK 支持 SSO 时有效
     */
//    private SsoHandler mSsoHandler;
    /**
     * 封装了 "access_token"，"expires_in"，"refresh_token"，并提供了他们的管理功能
     */
//    private Oauth2AccessToken mAccessToken;

    @Bind(R.id.login_password)
    EditText etPassword;
    @Bind(R.id.login_mobile)
    EditText etMobile;
    @Bind(R.id.login_register)
    TextView tvRegister;
    @Bind(R.id.login_forget)
    TextView tvForget;
    @Bind(R.id.login_btn)
    Button bLogin;
    @Bind(R.id.login_wechat)
    ImageView ivWeChat;
    @Bind(R.id.login_qq)
    ImageView ivQQ;
    @Bind(R.id.login_weibo)
    ImageView ivWeiBo;

    PlatformActionListener platformActionListener = new PlatformActionListener() {
        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//            showToast("1");
            if (platform.getName() == SinaWeibo.NAME) {
                Api.async_login_auto(platform.getDb().getUserId(), LoginActivity.TYPE_WEIBO, weiboLoginHandler);
            } else if (platform.getName() == Wechat.NAME) {
                Api.async_login_auto(platform.getDb().getUserId(), LoginActivity.TYPE_WX, wxBindHanlder);
            }
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
            showToast("系统或网络错误，请重试");
        }

        @Override
        public void onCancel(Platform platform, int i) {
            showToast("用户取消授权操作");
        }
    };

    PlatformActionListener infoPlatformActionListener = new PlatformActionListener() {
        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//            showToast("1");
            if (platform.getName() == SinaWeibo.NAME) {
                Api.alter_info(AppContext.getInstance().getProperty("user.code"), "", hashMap.get("screen_name").toString(),
                        hashMap.get("location").toString(), hashMap.get("gender").toString() == "m" ? "男" : "女", "", hashMap.get("profile_image_url").toString(),
                        alterInfoHandler);
            } else if (platform.getName() == Wechat.NAME) {
                Api.alter_info(AppContext.getInstance().getProperty("user.code"), "", hashMap.get("nickname").toString(),
                        hashMap.get("province").toString() + hashMap.get("city").toString(), hashMap.get("sex").toString().equals("1") ? "男" : "女", "", hashMap.get("headimgurl").toString(),
                        alterInfoHandler);
            }
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
            showToast("系统或网络错误，请重试");
        }

        @Override
        public void onCancel(Platform platform, int i) {
            showToast("用户取消操作");
        }
    };

    AsyncHttpResponseHandler wxBindHanlder = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            try {
                Result result = new Result(responseBody);
                if (result.getStatus() > 0) {
                    User user = JsonUtils.fromJson(result.getContent(), User.class);
                    AppContext.saveUserInfo(user);
                    AppContext.saveCookies(headers);
                    LoginActivity.showToast(result.getTips());

                    if (StringUtils.isEmpty(user.getUser_name())) {
                        Platform wechat = ShareSDK.getPlatform(LoginActivity.this, Wechat.NAME);
                        wechat.setPlatformActionListener(infoPlatformActionListener);
                        wechat.showUser(wechat.getDb().getUserId());

                    }

                    bindMobile();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//            String result = new String(responseBody);
            showToast(R.string.common_error_network);
        }

        @Override
        public void onFinish() {
            super.onFinish();
        }
    };

    AsyncHttpResponseHandler alterInfoHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
                } else {
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        }
    };

  /*  RequestListener weiboShow = new RequestListener() {
        @Override
        public void onComplete(String s) {

            WeiBoUser weiBoUser = JsonUtils.fromJson(s, WeiBoUser.class);

            Api.alter_info(AppContext.getInstance().getProperty("user.code"), "", weiBoUser.getScreen_name(),
                    weiBoUser.getLocation(), weiBoUser.getGender2(), "", weiBoUser.getProfile_image_url(),
                    alterInfoHandler);

//            showToast(s);
         *//*   Api.alter_info(AppContext.getInstance().getProperty("user.code"), "", wxUser.getNickname(),
                    wxUser.getProvince() + wxUser.getCity(), wxUser.getSexText(), "", wxUser.getHeadimgurl(),
                    alterInfoHandler);*//*
        }

        @Override
        public void onWeiboException(WeiboException e) {
            e.printStackTrace();
            showToast("应用未通过审核，无法获得用户信息");
        }
    };*/


    AsyncHttpResponseHandler loginHandler = new SimpleHandler(this) {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
//                    TLog.log(result.getContent() + result.getTips());
                    LoginActivity.showToast(result.getTips());
                    User user = JsonUtils.fromJson(result.getContent(), User.class);
                    AppContext.saveUserInfo(user);
                    AppContext.saveCookies(headers);

                    LoginActivity.this.jump(MainActivity.class);
//                    LoginActivity.this.jump(MyInfoActivity.class);
               /*     Bundle bundle = new Bundle();
                    bundle.putString("url", "http://freshlocpack1.gotoip1.com/user.php?module=Activity&api=activity_show&activity_id=9");
                    LoginActivity.this.jump(WebActivity.class, bundle);*/
                    AppManager.getAppManager().finishActivity();
                } else {
//                    LoginActivity.showToast(result.getTips());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    SimpleHandler weiboLoginHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
//                    TLog.log(result.getContent() + result.getTips());
                    LoginActivity.showToast(result.getTips());
                    User user = JsonUtils.fromJson(result.getContent(), User.class);
                    AppContext.saveUserInfo(user);
                    AppContext.saveCookies(headers);

                    if (StringUtils.isEmpty(user.getUser_name())) {

                        Platform weibo = ShareSDK.getPlatform(LoginActivity.this, SinaWeibo.NAME);
                        weibo.setPlatformActionListener(infoPlatformActionListener);
                        weibo.showUser(weibo.getDb().getUserId());//执行登录，登录后在回调里面获取用户资料

//weibo.showUser(“3189087725”);//获取账号为“3189087725”的资料

                   /*     WXApi.WXUserinfo(AppContext.getInstance().getProperty("wx.access_token"),
                                AppContext.getInstance().getProperty("wx.openid"), userInfoHandler);

                        UsersAPI usersAPI = new UsersAPI(LoginActivity.this, ConstantUtils.WEIBO_APP_KEY,
                                mAccessToken);
                        usersAPI.show(Long.parseLong(AppContext.getInstance().getProperty("weibo.openid")), weiboShow);*/
                    }
                    bindMobile();
                } else {
//                    LoginActivity.showToast(result.getTips());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected int getToolBarTitle() {
        return R.string.login;
    }

    @Override
    public void initView() {
        tvRegister.setOnClickListener(this);
        tvForget.setOnClickListener(this);
        bLogin.setOnClickListener(this);
        ivWeChat.setOnClickListener(this);
        ivQQ.setOnClickListener(this);
        ivWeiBo.setOnClickListener(this);
    }

    @Override
    public void initData() {
        weiboLoginHandler.setContext(this);

        String m = AppContext.getInstance()
                .getProperty("user.user_mobile");
        if (!StringUtils.isEmpty(m)) {

            etMobile.setText(m);
            etMobile.setSelection(m.length());
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();

        Bundle b = new Bundle();
        switch (id) {
            case R.id.login_btn:
                if (check()) {
                    showWaitDialog();
                    Api.login(etMobile.getText().toString(), etPassword.getText().toString(), loginHandler);
                }
                break;
            case R.id.login_register:
                b.putInt("type", PasswordActivtyType.REGISTER.getValue());
                jump(RegisterActivity.class, b);
                break;
            case R.id.login_forget:
                b.putInt("type", PasswordActivtyType.FORGET.getValue());
                jump(RegisterActivity.class, b);
                break;
            case R.id.login_wechat:
                wechatLogin();
                break;
            case R.id.login_qq:
                qqLogin();
                break;
            case R.id.login_weibo:
                weiboLogin();
                break;
        }
    }

    void wechatLogin() {
        LoginActivity.showToast("正在打开微信，请稍等");

        Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
        wechat.SSOSetting(false);  //设置false表示使用SSO授权方式
        wechat.setPlatformActionListener(platformActionListener); // 设置分享事件回调
        wechat.authorize();

/*        IWXAPI api = AppContext.WXapi;

        if (!api.isWXAppInstalled()) {
            showToast("请先安装微信应用");
            return;
        }
        if (!api.isWXAppSupportAPI()) {
            showToast("请先更新微信应用");
            return;
        }

        // 将该app注册到微信
        api.registerApp(ConstantUtils.WX_APP_ID);


        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wx_login";
        api.sendReq(req);*/
    }

    void qqLogin() {
        mTencent = Tencent.createInstance(ConstantUtils.QQ_APP_ID, this.getApplicationContext());

        if (!mTencent.isSessionValid()) {
            mTencent.login(this, "all", new AuthorListener());
        }
    }

    void weiboLogin() {
        LoginActivity.showToast("正在打开微博，请稍等");

        Platform weibo = ShareSDK.getPlatform(SinaWeibo.NAME);
        weibo.SSOSetting(false);  //设置false表示使用SSO授权方式
        weibo.setPlatformActionListener(platformActionListener); // 设置分享事件回调
        weibo.authorize();
//移除授权
//weibo.removeAccount();

 /*       mAuthInfo = new AuthInfo(this, ConstantUtils.WEIBO_APP_KEY, ConstantUtils.WEIBO_REDIRECT_URL, ConstantUtils.WEIBO_SCOPE);
        mSsoHandler = new SsoHandler(LoginActivity.this, mAuthInfo);

        // SSO 授权, ALL IN ONE   如果手机安装了微博客户端则使用客户端授权,没有则进行网页授权
        mSsoHandler.authorize(new AuthListener());*/
    }

    private boolean check() {
        String m = etMobile.getText().toString();
        String p = etPassword.getText().toString();

        if (StringUtils.isEmpty(m)) {
            showToast(R.string.login_mobile_error_null);
            return false;
        }
        if (StringUtils.isEmpty(p)) {
            showToast(R.string.login_password_error_null);
            return false;
        }
        return true;
    }

    class AuthorListener implements IUiListener {

        @Override
        public void onCancel() {
//            KJLoger.debug(getClass().getName() + "用户取消登陆");
        }

        @Override
        public void onComplete(Object arg0) {
            // packQQLoginBean(user, obj);
            LoginActivity.showToast("成功"); // 服务器端暂无
        }

        @Override
        public void onError(UiError error) {
//            KJLoger.debug(getClass().getName() + "登陆失败" + error.errorDetail);
        }
    }

   /* */

    /**
     * 微博认证授权回调类。
     * 1. SSO 授权时，需要在 {@link #onActivityResult} 中调用 {@link SsoHandler#authorizeCallBack} 后，
     * 该回调才会被执行。
     * 2. 非 SSO 授权时，当授权结束后，该回调就会被执行。
     * 当授权成功后，请保存该 access_token、expires_in、uid 等信息到 SharedPreferences 中。
     *//*
    class AuthListener implements WeiboAuthListener {

        @Override
        public void onComplete(Bundle values) {
            // 从 Bundle 中解析 Token
            mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            //从这里获取用户输入的 电话号码信息
//            String phoneNum = mAccessToken.getPhoneNum();
            if (mAccessToken.isSessionValid()) {
                AppContext.saveWX(mAccessToken);
//                mAccessToken.getUid();
                Api.async_login_auto(mAccessToken.getUid(), LoginActivity.TYPE_WEIBO, weiboLoginHandler);
          *//*      // 显示 Token
                updateTokenView(false);

                // 保存 Token 到 SharedPreferences
                AccessTokenKeeper.writeAccessToken(WBAuthActivity.this, mAccessToken);
                Toast.makeText(WBAuthActivity.this,
                        R.string.weibosdk_demo_toast_auth_success, Toast.LENGTH_SHORT).show();*//*
            } else {
                // 以下几种情况，您会收到 Code：
                // 1. 当您未在平台上注册的应用程序的包名与签名时；
                // 2. 当您注册的应用程序包名与签名不正确时；
                // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                String code = values.getString("code");
            }
        }

        @Override
        public void onCancel() {
            LoginActivity.showToast(R.string.weibosdk_demo_toast_auth_canceled);
        }

        @Override
        public void onWeiboException(WeiboException e) {
            LoginActivity.showToast("Auth exception : " + e.getMessage());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }*/

    void bindMobile() {
        if (StringUtils.isEmpty(AppContext.getInstance().getProperty("user.user_mobile"))) {
            Bundle b = new Bundle();
            b.putInt("type", PasswordActivtyType.BIND.getValue());
            jump(RegisterActivity.class, b);
        } else {
            LoginActivity.this.jump(MainActivity.class);
        }

        AppManager.getAppManager().finishActivity();
    }
}
